<div class="tmd-doc">
<h1 class="tmd-header-1">
Interfaces in Go
</h1>
<p></p>
<div class="tmd-usual">
Interface types are one special kind of type in Go. Interfaces play several important roles in Go. Fundamentally, interface types make Go support value boxing. Consequently, through value boxing, reflection and polymorphism get supported.
</div>
<p></p>
<div class="tmd-usual">
Since version 1.18, Go has already supported custom generics. In custom generics, an interface type could be (always) also used as type constraints. In fact, all type constraints are actually interface types. Before Go 1.18, all interface types may be used as value types. But since Go 1.18, some interface types may be only used as type constraints. Interface types which may be used as value types are called basic interface types.
</div>
<p></p>
<div class="tmd-usual">
This article was mainly written before Go supports custom generics, so it mainly talks about basic interfaces. About constraint-only interface types, please read the <a href="https://go101.org/generics/101.html">Go generics 101</a> book for details.
</div>
<p></p>
<p></p>
<h3 class="tmd-header-3">
Interface Types and Type Sets
</h3>
<p></p>
<div class="tmd-usual">
An interface type defines some (type) requirements. All non-interface types satisfying these requirements form a type set, which is called the type set of the interface type.
</div>
<p></p>
<div class="tmd-usual">
The requirements defined for an interface type are expressed by embedding some interface elements in the interface type. Currently (Go 1.25), there are two kinds of interface elements, method elements and type elements.
</div>
<p></p>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
A method element presents as a <a href="method.html#method-set">method specification</a>. A method specification embedded in an interface type may not use the blank identifier <code class="tmd-code-span">_</code> as its name.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
A type element may be a type name, a type literal, an approximation type, or a type union. The current article doesn't talk much about the latter two and only talks about type names and literals which denote interface types.
</div>
</li>
</ul>
<p></p>
<p></p>
<div class="tmd-usual">
For example, the predeclared <a href="https://golang.org/pkg/builtin/#error"><code class="tmd-code-span">error</code> interface type</a>, which definition is shown below, embeds a method specification <code class="tmd-code-span">Error() string</code>. In the definition, <code class="tmd-code-span">interface{...}</code> is called an interface type literal and the word <code class="tmd-code-span">interface</code> is a keyword in Go.
</div>
<p></p>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">type error interface {
        Error() string
}
</code></pre>
<p></p>
<div class="tmd-usual">
We may also say the <code class="tmd-code-span">error</code> interface type (directly) specifies a method <code class="tmd-code-span">Error() string</code>. Its type set is composed of all non-interface types which have a <a href="method.html">method</a> with the specification <code class="tmd-code-span">Error() string</code>. In theory, the type set is infinite. Surely, for a specified Go project, it is finite.
</div>
<p></p>
<p></p>
<div class="tmd-usual">
The following are some other interface type definitions and alias declarations.
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">// This interface directly specifies two methods and
// embeds two other interface types, one of which
// is a type name and the other is a type literal.
type ReadWriteCloser = interface {
	Read(buf []byte) (n int, err error)
	Write(buf []byte) (n int, err error)
	error                      // a type name
	interface{ Close() error } // a type literal
}

// This interface embeds an approximation type. Its type
// set includes all types whose underlying type is []byte.
type AnyByteSlice = interface {
	~[]byte
}

// This interface embeds a type union. Its type set includes
// 6 types: uint, uint8, uint16, uint32, uint64 and uintptr.
type Unsigned interface {
	uint | uint8 | uint16 | uint32 | uint64 | uintptr
}
</code></pre>
<p></p>
<div class="tmd-usual">
Embedding an interface type (denoted by either a type name or a type literal) in another one is equivalent to (recursively) expanding the elements in the former into the latter. For example, the interface type denoted by the type alias <code class="tmd-code-span">ReadWriteCloser</code> is equivalent to the interface type denoted by the following literal, which directly specifies four methods.
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">interface {
	Read(buf []byte) (n int, err error)
	Write(buf []byte) (n int, err error)
	Error() string
	Close() error
}
</code></pre>
<p></p>
<div class="tmd-usual">
The type set of the above interface type is composed of all non-interface types which at least have the four methods specified by the interface type. The type set is also infinite. It is definitely a subset of the type set of the <code class="tmd-code-span">error</code> interface type.
</div>
<p></p>
<div class="tmd-usual">
Please note that, before Go 1.18, only interface type names may be embedded in interface types.
</div>
<p></p>
<div class="tmd-usual">
The interface types shown in the following code are all called blank interface types, which embeds nothing and doesn't specify any methods.
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">// The unnamed blank interface type.
interface{}
	
// Nothing is a defined blank interface type.
type Nothing interface{}
</code></pre>
<p></p>
<div class="tmd-usual">
In fact, Go 1.18 introduced a predeclared alias, <code class="tmd-code-span">any</code>, which denotes the blank interface type <code class="tmd-code-span">interface{}</code>.
</div>
<p></p>
<div class="tmd-usual">
The type set of a blank interface type is composed of all non-interface types.
</div>
<p></p>
<h3 class="tmd-header-3">
Method Sets of Types
</h3>
<p></p>
<div class="tmd-usual">
Each type has a <a href="method.html#method-set">method set</a> associated with it.
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
For a non-interface type, its method set is composed of the specifications of all <a href="method.html">the methods (either explicit or implicit ones) declared</a> for it.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
For an interface type, its method set is composed of all the method specifications it specifies, either directly or indirectly through embedding other types.
</div>
</li>
</ul>
<p></p>
<p></p>
<div class="tmd-usual">
In the examples shown in the last section,
</div>
<p></p>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
the method set of the interface type denoted by <code class="tmd-code-span">ReadWriteCloser</code> contains four methods.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
the method set of the predeclared interface type <code class="tmd-code-span">error</code> contains only one method.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
the method set of a blank interface type is empty.
</div>
</li>
</ul>
<p></p>
<div class="tmd-usual">
For convenience, the method set of a type is often also called the method set of any value of the type.
</div>
<p></p>
<h3 class="tmd-header-3">
Basic Interface Types
</h3>
<p></p>
<div class="tmd-usual">
Basic interface types are the interface types which may be used as value types. A non-basic interface type is also called a constraint-only interface type.
</div>
<p></p>
<div class="tmd-usual">
Currently (Go 1.25), every basic interface type could be defined entirely by a method set (may be empty). In other words, a basic interface type doesn't need type elements to be defined.
</div>
<p></p>
<div class="tmd-usual">
In the examples shown in the section before the last, the interface type denoted by alias <code class="tmd-code-span">ReadWriteCloser</code> is a basic type, but the <code class="tmd-code-span">Unsigned</code> interface type and the type denoted by alias <code class="tmd-code-span">AnyByteSlice</code> are not. The latter two are both constraint-only interface types.
</div>
<p></p>
<div class="tmd-usual">
Blank interface types and the predeclared <code class="tmd-code-span">error</code> interface type are also all basic interface types.
</div>
<p></p>
<div class="tmd-usual">
Two unnamed basic interface types are identical if their method sets are identical. Please note, non-exported methods (which names are non-exported identifiers) from different packages are always viewed as two different methods, even if their names are identical.
</div>
<p></p>
<h3 id="implementation" class="tmd-header-3">
Implementations
</h3>
<p></p>
<div class="tmd-usual">
If a non-interface type is contained in the type set of an interface type, then we say the non-interface type implements the interface type. If the type set of an interface type is a subset of another interface type, then we say the former one implements the latter one.
</div>
<p></p>
<div class="tmd-usual">
An interface type always implements itself, as a type set is always a subset (or superset) of itself. Similarly, two interface types with the same method set implement each other. In fact, two unnamed interface types are identical if their type sets are identical.
</div>
<p></p>
<div class="tmd-usual">
If a type <code class="tmd-code-span">T</code> implements an interface type <code class="tmd-code-span">X</code>, then the method set of <code class="tmd-code-span">T</code> must be superset of <code class="tmd-code-span">X</code>, whether <code class="tmd-code-span">T</code> is an interface type or an non-interface type. For example, in the examples provided in a previous section, the interface type denoted by <code class="tmd-code-span">ReadWriteCloser</code> implements the <code class="tmd-code-span">error</code> interface type.
</div>
<p></p>
<div class="tmd-usual">
Implementations are all implicit in Go. The compiler does not require implementation relations to be specified in code explicitly. There is not an <code class="tmd-code-span">implements</code> keyword in Go. Go compilers will check the implementation relations automatically as needed.
</div>
<p></p>
<div class="tmd-usual">
For example, in the following example, the method sets of struct pointer type <code class="tmd-code-span">*Book</code>, integer type <code class="tmd-code-span">MyInt</code> and pointer type <code class="tmd-code-span">*MyInt</code> all contain the method specification <code class="tmd-code-span">About() string</code>, so they all implement the above mentioned interface type <code class="tmd-code-span">Aboutable</code>.
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">type Aboutable interface {
	About() string
}

type Book struct {
	name string
	// more other fields ...
}

func (book *Book) About() string {
	return "Book: " + book.name
}

type MyInt int

func (MyInt) About() string {
	return "I'm a custom integer value"
}
</code></pre>
<p></p>
<div class="tmd-usual">
The implicit implementation design makes it possible to let types defined in other library packages, such as standard packages, passively implement some interface types declared in user packages. For example, if we declare an interface type as the following one, then the type <code class="tmd-code-span">DB</code> and type <code class="tmd-code-span">Tx</code> declared in <a href="https://golang.org/pkg/database/sql/">the <code class="tmd-code-span">database/sql</code> standard package</a> will both implement the interface type automatically, for they both have the three corresponding methods specified in the interface.
</div>
<p></p>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">import "database/sql"

...

type DatabaseStorer interface {
	Exec(query string, args ...interface{}) (sql.Result, error)
	Prepare(query string) (*sql.Stmt, error)
	Query(query string, args ...interface{}) (*sql.Rows, error)
}
</code></pre>
<p></p>
<div class="tmd-usual">
Note, as the type set of a blank interface type is composed of all non-interface types, so all types implement any blank interface type. This is an important fact in Go.
</div>
<p></p>
<h3 id="boxing" class="tmd-header-3">
Value Boxing
</h3>
<p></p>
<div class="tmd-usual">
Again, currently (Go 1.25), the types of interface values must be basic interface types. In the remaining contents of the current article, when a value type is mentioned, the value type may be non-interface type or a basic interface type. It is never a constraint-only interface type.
</div>
<p></p>
<div class="tmd-usual">
We can view each interface value as a box to encapsulate a non-interface value. To box/encapsulate a non-interface value into an interface value, the type of the non-interface value must implement the type of the interface value.
</div>
<p></p>
<div class="tmd-usual">
If a type <code class="tmd-code-span">T</code> implements a (basic) interface type <code class="tmd-code-span">I</code>, then any value of type <code class="tmd-code-span">T</code> can be implicitly converted to type <code class="tmd-code-span">I</code>. In other words, any value of type <code class="tmd-code-span">T</code> is <a href="constants-and-variables.html#assignment">assignable</a> to (modifiable) values of type <code class="tmd-code-span">I</code>. When a <code class="tmd-code-span">T</code> value is converted (assigned) to an <code class="tmd-code-span">I</code> value,
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
if type <code class="tmd-code-span">T</code> is a non-interface type, then a copy of the <code class="tmd-code-span">T</code> value is boxed (or encapsulated) into the result (or destination) <code class="tmd-code-span">I</code> value. The time complexity of the copy is <span class="tmd-italic"><code class="tmd-code-span">O(n)</code></span>, where <code class="tmd-code-span">n</code> is the size of copied <code class="tmd-code-span">T</code> value. <span class="tmd-italic">(The standard Go compiler makes several optimizations to reduce the costs in boxing values satisfying certain conditions. Please read the "Interfaces" chapter in the </span><a href="https://go101.org/optimizations/101.html"><span class="tmd-italic">Go Optimizations 101</span></a><span class="tmd-italic"> book for such optimizations.)</span>
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
if type <code class="tmd-code-span">T</code> is also an interface type, then a copy of the value boxed in the <code class="tmd-code-span">T</code> value is boxed (or encapsulated) into the result (or destination) <code class="tmd-code-span">I</code> value. The standard Go compiler makes an optimization here, so the time complexity of the copy is <span class="tmd-italic"><code class="tmd-code-span">O(1)</code></span>, instead of <span class="tmd-italic"><code class="tmd-code-span">O(n)</code></span>.
</div>
</li>
</ul>
<p></p>
<p></p>
<div class="tmd-usual">
The type information of the boxed value is also stored in the result (or destination) interface value. (This will be further explained below.)
</div>
<p></p>
<div class="tmd-usual">
When a value is boxed in an interface value, the value is called the <span class="tmd-bold"><span class="tmd-italic">dynamic value</span></span> of the interface value. The type of the dynamic value is called the <span class="tmd-bold"><span class="tmd-italic">dynamic type</span></span> of the interface value.
</div>
<p></p>
<div class="tmd-usual">
The direct part of the dynamic value of an interface value is immutable, though we can replace the dynamic value of an interface value with another dynamic value.
</div>
<p></p>
<div class="tmd-usual">
In Go, the zero values of any interface type are represented by the predeclared <code class="tmd-code-span">nil</code> identifier. Nothing is boxed in a nil interface value. Assigning an untyped <code class="tmd-code-span">nil</code> to an interface value will clear the dynamic value boxed in the interface value.
</div>
<p></p>
<div class="tmd-usual">
<span class="tmd-italic">(Note, the zero values of many non-interface types in Go are also represented by <code class="tmd-code-span">nil</code> in Go. Non-interface nil values can also be boxed in interface values. An interface value boxing a nil non-interface value still boxes something, so it is not a nil interface value.)</span>
</div>
<p></p>
<div class="tmd-usual">
As any type implements all blank interface types, so any non-interface value can be boxed in (or assigned to) a blank interface value. For this reason, blank interface types can be viewed as the <code class="tmd-code-span">any</code> type in many other languages.
</div>
<p></p>
<div class="tmd-usual">
When an untyped value (except untyped <code class="tmd-code-span">nil</code> values) is assigned to a blank interface value, the untyped value will be first converted to its default type. (In other words, we can think the untyped value is deduced as a value of its default type).
</div>
<p></p>
<div class="tmd-usual">
Let's view an example which demonstrates some assignments with interface values as the destinations.
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

type Aboutable interface {
	About() string
}

// Type *Book implements Aboutable.
type Book struct {
	name string
}
func (book *Book) About() string {
	return "Book: " + book.name
}

func main() {
	// A *Book value is boxed into an
	// interface value of type Aboutable.
	var a Aboutable = &amp;Book{"Go 101"}
	fmt.Println(a) // &amp;{Go 101}

	// i is a blank interface value.
	var i interface{} = &amp;Book{"Rust 101"}
	fmt.Println(i) // &amp;{Rust 101}

	// Aboutable implements interface{}.
	i = a
	fmt.Println(i) // &amp;{Go 101}
}
</code></pre>
<p></p>
<div class="tmd-usual">
Please note, the prototype of the <code class="tmd-code-span">fmt.Println</code> function used many times in previous articles is
</div>
<p></p>
<pre class="tmd-code disable-line-numbers111">
<code class="language-go">func Println(a ...interface{}) (n int, err error)
</code></pre>
<p></p>
<div class="tmd-usual">
This is why a <code class="tmd-code-span">fmt.Println</code> function calls can take arguments of any types.
</div>
<p></p>
<div class="tmd-usual">
The following is another example which shows how a blank interface value is used to box values of any non-interface type.
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	var i interface{}
	i = []int{1, 2, 3}
	fmt.Println(i) // [1 2 3]
	i = map[string]int{"Go": 2012}
	fmt.Println(i) // map[Go:2012]
	i = true
	fmt.Println(i) // true
	i = 1
	fmt.Println(i) // 1
	i = "abc"
	fmt.Println(i) // abc

	// Clear the boxed value in interface value i.
	i = nil
	fmt.Println(i) // &lt;nil&gt;
}
</code></pre>
<p></p>
<div class="tmd-usual">
Go compilers will build a global table which contains the information of each type at compile time. The information includes what <a href="type-system-overview.html#type-kinds">kind</a> a type is, what methods and fields a type owns, what the element type of a container type is, type sizes, etc. The global table will be loaded into memory when a program starts.
</div>
<p></p>
<p></p>
<div class="tmd-usual">
At run time, when a non-interface value is boxed into an interface value, the Go runtime (at least for the standard Go runtime) will analyze and build the implementation information for the type pair of the two values, and store the implementation information in the interface value. The implementation information for each non-interface type and interface type pair will only be built once and cached in a global map for execution efficiency consideration. The number of entries of the global map never decreases. In fact, a non-nil interface value just uses <a href="value-part.html#interface-structure">an internal pointer field which references a cached implementation information entry</a>.
</div>
<p></p>
<p></p>
<div class="tmd-usual">
The implementation information for each (interface type, dynamic type) pair includes two pieces of information:
</div>
<ol class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
the information of the dynamic type (a non-interface type)
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
and a method table (a slice) which stores all the corresponding methods specified by the interface type and declared for the non-interface type (the dynamic type).
</div>
</li>
</ol>
<p></p>
<div class="tmd-usual">
These two pieces of information are essential for implementing two important features in Go:
</div>
<ol class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
The dynamic type information is the key to implement <a href="#reflection">reflection</a> in Go.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
The method table information is the key to implement polymorphism (polymorphism will be explained in the next section).
</div>
</li>
</ol>
<p></p>
<p></p>
<h3 id="polymorphism" class="tmd-header-3">
Polymorphism
</h3>
<p></p>
<div class="tmd-usual">
Polymorphism is one key functionality provided by interfaces, and it is an important feature of Go.
</div>
<p></p>
<div class="tmd-usual">
When a non-interface value <code class="tmd-code-span">t</code> of a type <code class="tmd-code-span">T</code> is boxed in an interface value <code class="tmd-code-span">i</code> of type <code class="tmd-code-span">I</code>, calling a method specified by the interface type <code class="tmd-code-span">I</code> on the interface value <code class="tmd-code-span">i</code> will call the corresponding method declared for the non-interface type <code class="tmd-code-span">T</code> on the non-interface value <code class="tmd-code-span">t</code> actually. In other words, <span class="tmd-bold">calling the method of an interface value will actually call the corresponding method of the dynamic value of the interface value</span>. For example, calling method <code class="tmd-code-span">i.m</code> will call method <code class="tmd-code-span">t.m</code> actually. With different dynamic values of different dynamic types boxed into the interface value, the interface value behaves differently. This is called polymorphism.
</div>
<p></p>
<div class="tmd-usual">
When method <code class="tmd-code-span">i.m</code> is called, the method table in the implementation information stored in <code class="tmd-code-span">i</code> will be looked up to find and call the corresponding method <code class="tmd-code-span">t.m</code>. The method table is a slice and the lookup is just a slice element indexing, so this is quick.
</div>
<p></p>
<div class="tmd-usual">
<span class="tmd-italic">(Note, calling methods on a nil interface value will panic at run time, for there are no available declared methods to be called.)</span>
</div>
<p></p>
<div class="tmd-usual">
An example:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

type Filter interface {
	About() string
	Process([]int) []int
}

// UniqueFilter is used to remove duplicate numbers.
type UniqueFilter struct{}
func (UniqueFilter) About() string {
	return "remove duplicate numbers"
}
func (UniqueFilter) Process(inputs []int) []int {
	outs := make([]int, 0, len(inputs))
	pusheds := make(map[int]bool)
	for _, n := range inputs {
		if !pusheds[n] {
			pusheds[n] = true
			outs = append(outs, n)
		}
	}
	return outs
}

// MultipleFilter is used to keep only
// the numbers which are multiples of
// the MultipleFilter as an int value.
type MultipleFilter int
func (mf MultipleFilter) About() string {
	return fmt.Sprintf("keep multiples of %v", mf)
}
func (mf MultipleFilter) Process(inputs []int) []int {
	var outs = make([]int, 0, len(inputs))
	for _, n := range inputs {
		if n % int(mf) == 0 {
			outs = append(outs, n)
		}
	}
	return outs
}

// With the help of polymorphism, only one
// "filterAndPrint" function is needed.
func filterAndPrint(fltr Filter, unfiltered []int) []int {
	// Calling the methods of "fltr" will call the
	// methods of the value boxed in "fltr" actually.
	filtered := fltr.Process(unfiltered)
	fmt.Println(fltr.About() + ":\n\t", filtered)
	return filtered
}

func main() {
	numbers := []int{12, 7, 21, 12, 12, 26, 25, 21, 30}
	fmt.Println("before filtering:\n\t", numbers)

	// Three non-interface values are boxed into
	// three Filter interface slice element values.
	filters := []Filter{
		UniqueFilter{},
		MultipleFilter(2),
		MultipleFilter(3),
	}

	// Each slice element will be assigned to the
	// local variable "fltr" (of interface type
	// Filter) one by one. The value boxed in each
	// element will also be copied into "fltr".
	for _, fltr := range filters {
		numbers = filterAndPrint(fltr, numbers)
	}
}
</code></pre>
<p></p>
<div class="tmd-usual">
The output:
</div>
<pre class="tmd-code output">
before filtering:
	 [12 7 21 12 12 26 25 21 30]
remove duplicate numbers:
	 [12 7 21 26 25 30]
keep multiples of 2:
	 [12 26 30]
keep multiples of 3:
	 [12 30]
</pre>
<p></p>
<div class="tmd-usual">
In the above example, polymorphism makes it unnecessary to write one <code class="tmd-code-span">filterAndPrint</code> function for each filter type.
</div>
<p></p>
<div class="tmd-usual">
Besides the above benefit, polymorphism also makes it possible for the developers of a library code package to declare an exported interface type and declare a function (or method) which has a parameter of the interface type, so that a user of the package can declare a type, which implements the interface type, in user code and pass arguments of the user type to calls to the function (or method). The developers of the code package don't need to care about how the user type is declared, as long as the user type satisfies the behaviors specified by the interface type declared in the library code package.
</div>
<p></p>
<div class="tmd-usual">
In fact, polymorphism is not an essential feature for a language. There are alternative ways to achieve the same job, such as callback functions. But the polymorphism way is cleaner and more elegant.
</div>
<p></p>
<h3 id="reflection" class="tmd-header-3">
Reflection
</h3>
<p></p>
<div class="tmd-usual">
The dynamic type information stored in an interface value can be used to inspect the dynamic value of the interface value and manipulate the values referenced by the dynamic value. This is called reflection in programming.
</div>
<p></p>
<div class="tmd-usual">
This article will not explain the functionalities provided by <a href="https://golang.org/pkg/reflect/">the <code class="tmd-code-span">reflect</code> standard package</a>. Please read <a href="reflection.html">reflections in Go</a> to get how to use that package. Below will only introduce the built-in reflection functionalities in Go. In Go, built-in reflections are achieved with type assertions and <code class="tmd-code-span">type-switch</code> control flow code blocks.
</div>
<p></p>
<p></p>
<h4 id="type-assertion" class="tmd-header-4">
Type assertion
</h4>
<p></p>
<div class="tmd-usual">
There are four kinds of interface-value-involving value conversion cases in Go:
</div>
<ol class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
convert a non-interface value to an interface value, where the type of the non-interface value must implement the type of the interface value.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
convert an interface value to an interface value, where the type of the source interface value must implement the type of the destination interface value.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
convert an interface value to a non-interface value, where the type of the non-interface value must implement the type of the interface value.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
convert an interface value to an interface value, where the type of the source interface value doesn't implement the destination interface type, but the dynamic type of the source interface value might implement the destination interface type.
</div>
</li>
</ol>
<p></p>
<div class="tmd-usual">
We have already explained the first two kinds of cases. They both require that the source value type implements the destination interface type. The convertibility for the first two are verified at compile time.
</div>
<p></p>
<div class="tmd-usual">
Here will explain the later two kinds of cases. The convertibility for the later two are verified at run time, by using a syntax called <span class="tmd-bold"><span class="tmd-italic">type assertion</span></span>. In fact, the syntax also applies to the second kind of conversion in our above list.
</div>
<p></p>
<div class="tmd-usual">
The form of a type assertion expression is <code class="tmd-code-span">i.(T)</code>, where <code class="tmd-code-span">i</code> is an interface value and <code class="tmd-code-span">T</code> is a type name or a type literal. Type <code class="tmd-code-span">T</code> must be
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
either an arbitrary non-interface type,
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
or an arbitrary interface type.
</div>
</li>
</ul>
<p></p>
<div class="tmd-usual">
In a type assertion <code class="tmd-code-span">i.(T)</code>, <code class="tmd-code-span">i</code> is called the asserted value and <code class="tmd-code-span">T</code> is called the asserted type. A type assertion might succeed or fail.
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
In the case of <code class="tmd-code-span">T</code> being a non-interface type, if the dynamic type of <code class="tmd-code-span">i</code> exists and is identical to <code class="tmd-code-span">T</code>, then the assertion will succeed, otherwise, the assertion will fail. When the assertion succeeds, the evaluation result of the assertion is a copy of the dynamic value of <code class="tmd-code-span">i</code>. We can view assertions of this kind as value unboxing attempts.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
In the case of <code class="tmd-code-span">T</code> being an interface type, if the dynamic type of <code class="tmd-code-span">i</code> exists and implements <code class="tmd-code-span">T</code>, then the assertion will succeed, otherwise, the assertion will fail. When the assertion succeeds, a copy of the dynamic value of <code class="tmd-code-span">i</code> will be boxed into a <code class="tmd-code-span">T</code> value and the <code class="tmd-code-span">T</code> value will be used as the evaluation result of the assertion.
</div>
</li>
</ul>
<p></p>
<div class="tmd-usual">
When a type assertion fails, its evaluation result is a zero value of the asserted type.
</div>
<p></p>
<div class="tmd-usual">
By the rules described above, if the asserted value in a type assertion is a nil interface value, then the assertion will always fail.
</div>
<p></p>
<div class="tmd-usual">
For most scenarios, a type assertion is used as a single-value expression. However, when a type assertion is used as the only source value expression in an assignment, it can result in a second optional untyped boolean value and be viewed as a multi-value expression. The second optional untyped boolean value indicates whether or not the type assertion succeeds.
</div>
<p></p>
<div class="tmd-usual">
Note, if a type assertion fails and the type assertion is used as a single-value expression (the second optional bool result is absent), then a panic will occur.
</div>
<p></p>
<div class="tmd-usual">
An example which shows how to use type assertions (asserted types are non-interface types):
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	// Compiler will deduce the type of 123 as int.
	var x interface{} = 123

	// Case 1:
	n, ok := x.(int)
	fmt.Println(n, ok) // 123 true
	n = x.(int)
	fmt.Println(n) // 123

	// Case 2:
	a, ok := x.(float64)
	fmt.Println(a, ok) // 0 false

	// Case 3:
	a = x.(float64) // will panic
}
</code></pre>
<p></p>
<div class="tmd-usual">
Another example which shows how to use type assertions (asserted types are interface types):
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

type Writer interface {
	Write(buf []byte) (int, error)
}

type DummyWriter struct{}
func (DummyWriter) Write(buf []byte) (int, error) {
	return len(buf), nil
}

func main() {
	var x interface{} = DummyWriter{}
	var y interface{} = "abc"
	// Now the dynamic type of y is "string".
	var w Writer
	var ok bool

	// Type DummyWriter implements both
	// Writer and interface{}.
	w, ok = x.(Writer)
	fmt.Println(w, ok) // {} true
	x, ok = w.(interface{})
	fmt.Println(x, ok) // {} true

	// The dynamic type of y is "string",
	// which doesn't implement Writer.
	w, ok = y.(Writer)
	fmt.Println(w, ok) // &lt;nil&gt; false
	w = y.(Writer)     // will panic
}
</code></pre>
<p></p>
<div class="tmd-usual">
In fact, for an interface value <code class="tmd-code-span">i</code> with a dynamic type <code class="tmd-code-span">T</code>, the method call <code class="tmd-code-span">i.m(...)</code> is equivalent to the method call <code class="tmd-code-span">i.(T).m(...)</code>.
</div>
<p></p>
<h4 id="type-switch" class="tmd-header-4">
<code class="tmd-code-span">type-switch</code> control flow block
</h4>
<p></p>
<div class="tmd-usual">
The <code class="tmd-code-span">type-switch</code> code block syntax may be the weirdest syntax in Go. It can be viewed as the enhanced version of type assertion. A <code class="tmd-code-span">type-switch</code> code block is in some way similar to a <code class="tmd-code-span">switch-case</code> control flow code block. It looks like:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">switch aSimpleStatement; v := x.(type) {
case TypeA:
	...
case TypeB, TypeC:
	...
case nil:
	...
default:
	...
}
</code></pre>
<p></p>
<div class="tmd-usual">
The <code class="tmd-code-span">aSimpleStatement;</code> portion is optional in a <code class="tmd-code-span">type-switch</code> code block. <code class="tmd-code-span">aSimpleStatement</code> must be a <a href="expressions-and-statements.html#simple-statements">simple statement</a>. <code class="tmd-code-span">x</code> must be an interface value and it is called the asserted value. <code class="tmd-code-span">v</code> is called the assertion result, it must be present in a short variable declaration form.
</div>
<p></p>
<p></p>
<div class="tmd-usual">
Each <code class="tmd-code-span">case</code> keyword in a <code class="tmd-code-span">type-switch</code> block can be followed by the predeclared <code class="tmd-code-span">nil</code> identifier or a comma-separated list composed of at least one type name and type literal. None of such items (<code class="tmd-code-span">nil</code>, type names and type literals) may be duplicate in the same <code class="tmd-code-span">type-switch</code> code block.
</div>
<p></p>
<div class="tmd-usual">
If the type denoted by a type name or type literal following a <code class="tmd-code-span">case</code> keyword in a <code class="tmd-code-span">type-switch</code> code block is not an interface type, then it must implement the interface type of the asserted value.
</div>
<p></p>
<div class="tmd-usual">
Here is an example in which a <code class="tmd-code-span">type-switch</code> control flow code block is used.
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	values := []interface{}{
		456, "abc", true, 0.33, int32(789),
		[]int{1, 2, 3}, map[int]bool{}, nil,
	}
	for _, x := range values {
		// Here, v is declared once, but it denotes
		// different variables in different branches.
		switch v := x.(type) {
		case []int: // a type literal
			// The type of v is "[]int" in this branch.
			fmt.Println("int slice:", v)
		case string: // one type name
			// The type of v is "string" in this branch.
			fmt.Println("string:", v)
		case int, float64, int32: // multiple type names
			// The type of v is "interface{}",
			// the same as x in this branch.
			fmt.Println("number:", v)
		case nil:
			// The type of v is "interface{}",
			// the same as x in this branch.
			fmt.Println(v)
		default:
			// The type of v is "interface{}",
			// the same as x in this branch.
			fmt.Println("others:", v)
		}
		// Note, each variable denoted by v in the
		// last three branches is a copy of x.
	}
}
</code></pre>
<p></p>
<div class="tmd-usual">
The output:
</div>
<pre class="tmd-code output">
number: 456
string: abc
others: true
number: 0.33
number: 789
int slice: [1 2 3]
others: map[]
&lt;nil&gt;
</pre>
<p></p>
<div class="tmd-usual">
The above example is equivalent to the following in logic:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	values := []interface{}{
		456, "abc", true, 0.33, int32(789),
		[]int{1, 2, 3}, map[int]bool{}, nil,
	}
	for _, x := range values {
		if v, ok := x.([]int); ok {
			fmt.Println("int slice:", v)
		} else if v, ok := x.(string); ok {
			fmt.Println("string:", v)
		} else if x == nil {
			v := x
			fmt.Println(v)
		} else {
			_, isInt := x.(int)
			_, isFloat64 := x.(float64)
			_, isInt32 := x.(int32)
			if isInt || isFloat64 || isInt32 {
				v := x
				fmt.Println("number:", v)
			} else {
				v := x
				fmt.Println("others:", v)
			}
		}
	}
}
</code></pre>
<p></p>
<div class="tmd-usual">
<code class="tmd-code-span">type-switch</code> code blocks are similar to <code class="tmd-code-span">switch-case</code> code blocks in some aspects.
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
Like <code class="tmd-code-span">switch-case</code> blocks, in a <code class="tmd-code-span">type-switch</code> code block, there can be at most one <code class="tmd-code-span">default</code> branch.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
Like <code class="tmd-code-span">switch-case</code> blocks, in a <code class="tmd-code-span">type-switch</code> code block, if the <code class="tmd-code-span">default</code> branch is present, it can be the last branch, the first branch, or a middle branch.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
Like <code class="tmd-code-span">switch-case</code> blocks, a <code class="tmd-code-span">type-switch</code> code block may not contain any branches, it will be viewed as a no-op.
</div>
</li>
</ul>
<p></p>
<div class="tmd-usual">
But, unlike <code class="tmd-code-span">switch-case</code> code blocks, <code class="tmd-code-span">fallthrough</code> statements can't be used within branch blocks of a <code class="tmd-code-span">type-switch</code> code block.
</div>
<p></p>
<h3 class="tmd-header-3">
More About Interfaces in Go
</h3>
<p></p>
<p></p>
<h4 id="comparison" class="tmd-header-4">
Comparisons involving interface values
</h4>
<p></p>
<div class="tmd-usual">
There are two cases of comparisons involving interface values:
</div>
<ol class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
comparisons between a non-interface value and an interface value.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
comparisons between two interface values.
</div>
</li>
</ol>
<p></p>
<div class="tmd-usual">
For the first case, the type of the non-interface value must implement the type (assume it is <code class="tmd-code-span">I</code>) of the interface value, so the non-interface value can be converted to (boxed into) an interface value of <code class="tmd-code-span">I</code>. This means a comparison between a non-interface value and an interface value can be translated to a comparison between two interface values. So below only comparisons between two interface values will be explained.
</div>
<p></p>
<div class="tmd-usual">
Comparing two interface values is comparing their respective dynamic types and dynamic values actually.
</div>
<p></p>
<div class="tmd-usual">
The steps of comparing two interface values (with the <code class="tmd-code-span">==</code> operator):
</div>
<ol class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
if one of the two interface values is a nil interface value, then the comparison result is whether or not the other interface value is also a nil interface value.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
if the dynamic types of the two interface values are two different types, then the comparison result is <code class="tmd-code-span">false</code>.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
in the case where the dynamic types of the two interface values are the same type,
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
if the same dynamic type is an <a href="value-conversions-assignments-and-comparisons.html#comparison-rules">incomparable type</a>, a panic will occur.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
otherwise, the comparison result is the result of comparing the dynamic values of the two interface values.
</div>
</li>
</ul>
</li>
</ol>
<p></p>
<p></p>
<div class="tmd-usual">
In short, two interface values are equal only if one of the following conditions are satisfied.
</div>
<ol class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
They are both nil interface values.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
Their dynamic types are identical and comparable, and their dynamic values are equal to each other.
</div>
</li>
</ol>
<p></p>
<div class="tmd-usual">
By the rules, two interface values which dynamic values are both <code class="tmd-code-span">nil</code> may be not equal. An example:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	var a, b, c interface{} = "abc", 123, "a"+"b"+"c"
	// A case of step 2.
	fmt.Println(a == b) // false
	// A case of step 3.
	fmt.Println(a == c) // true

	var x *int = nil
	var y *bool = nil
	var ix, iy interface{} = x, y
	var i interface{} = nil
	// A case of step 2.
	fmt.Println(ix == iy) // false
	// A case of step 1.
	fmt.Println(ix == i) // false
	// A case of step 1.
	fmt.Println(iy == i) // false

	// []int is an incomparable type
	var s []int = nil
	i = s
	// A case of step 1.
	fmt.Println(i == nil) // false
	// A case of step 3.
	fmt.Println(i == i) // will panic
}
</code></pre>
<p></p>
<h4 class="tmd-header-4">
The internal structure of interface values
</h4>
<p></p>
<div class="tmd-usual">
For the official Go compiler/runtime, blank interface values and non-blank interface values are represented with two different internal structures. Please read <a href="value-part.html#interface-structure">value parts</a> for details.
</div>
<p></p>
<p></p>
<p></p>
<h4 class="tmd-header-4">
Values of <code class="tmd-code-span">[]T</code> can't be directly converted to <code class="tmd-code-span">[]I</code>, even if type <code class="tmd-code-span">T</code> implements interface type <code class="tmd-code-span">I</code>.
</h4>
<p></p>
<div class="tmd-usual">
For example, sometimes, we may need to convert a <code class="tmd-code-span">[]string</code> value to <code class="tmd-code-span">[]interface{}</code> type. Unlike some other languages, there is no direct way to make the conversion. We must make the conversion manually in a loop:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

func main() {
	words := []string{
		"Go", "is", "a", "high",
		"efficient", "language.",
	}

	// The prototype of fmt.Println function is
	// func Println(a ...interface{}) (n int, err error).
	// So words... can't be passed to it as the argument.

	// fmt.Println(words...) // not compile

	// Convert the []string value to []interface{}.
	iw := make([]interface{}, 0, len(words))
	for _, w := range words {
		iw = append(iw, w)
	}
	fmt.Println(iw...) // compiles okay
}
</code></pre>
<p></p>
<h4 class="tmd-header-4">
Each method specified in an interface type corresponds to an implicit function
</h4>
<p></p>
<div class="tmd-usual">
For each method with name <code class="tmd-code-span">m</code> in the method set defined by an interface type <code class="tmd-code-span">I</code>, compilers will implicitly declare a function named <code class="tmd-code-span">I.m</code>, which has one more input parameter, of type <code class="tmd-code-span">I</code>, than method <code class="tmd-code-span">m</code>. The extra parameter is the first input parameter of function <code class="tmd-code-span">I.m</code>. Assume <code class="tmd-code-span">i</code> is an interface value of <code class="tmd-code-span">I</code>, then the method call <code class="tmd-code-span">i.m(...)</code> is equivalent to the function call <code class="tmd-code-span">I.m(i, ...)</code>.
</div>
<p></p>
<div class="tmd-usual">
An example:
</div>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

import "fmt"

type I interface {
	m(int)bool
}

type T string
func (t T) m(n int) bool {
	return len(t) &gt; n
}

func main() {
	var i I = T("gopher")
	fmt.Println(i.m(5))                        // true
	fmt.Println(I.m(i, 5))                     // true
	fmt.Println(interface{m(int)bool}.m(i, 5)) // true

	// The following lines compile okay,
	// but will panic at run time.
	I(nil).m(5)
	I.m(nil, 5)
	interface {m(int) bool}.m(nil, 5)
}
</code></pre>
</div>
